﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using Dos.ORM;
using JFLogic.Logic.JF;
using JFLogic.Logic.Donee;
using JFLogic.Logic.JFSession;
using System.Collections;
using JFLogic.Logic.CodeRepo;
using System.Web.Security;
using JFLogic.Utils;
using JFLogic.Logic.Fail;

namespace JFLogic.Logic.Exchange
{
    public class ExchangeLogic
    {
        private int sessionTimeout = -30;
        public int Update(TB_Day_Exchage_Info pUser)
        {
            return DB.Context.Update<TB_Day_Exchage_Info>(pUser);
        }

        /// <summary>
        /// 登陆查询积分
        /// </summary>
        /// <param name="pUser"></param>
        /// <returns></returns>
        public int Insert(TB_Day_Exchage_Info pUser)
        {
            return DB.Context.Insert<TB_Day_Exchage_Info>(pUser);
        }

        /// <summary>
        /// 根据SessionId 获取实体
        /// </summary>
        /// <param name="sessionId"></param>
        /// <returns></returns>
        public TB_Day_Exchage_Info GetModelBySessionId(string sessionId)
        {
            return DB.Context.From<TB_Day_Exchage_Info>()
                .Where(d => (d.SessionId == sessionId))
                .First();
        }

        /// <summary>
        /// 检测sessionid是否已过期
        /// </summary>
        /// <param name="sessionId"></param>
        /// <returns>true 尚未过期 false 已经过期</returns>
        public TB_Day_Exchage_Info CheckSessionGetModel(string sessionId)
        {
            var where = new Where<TB_Day_Exchage_Info>();
            where.And(d => (d.SessionId == sessionId));
            where.And(d => (d.LoginTime > DateTime.Now.AddMinutes(sessionTimeout)));
            return DB.Context.From<TB_Day_Exchage_Info>()
                .Where(where)
                .First();
        }

        /// <summary>
        /// 检测sessionid是否已过期
        /// </summary>
        /// <param name="sessionId"></param>
        /// <returns>true 尚未过期 false 已经过期</returns>
        public bool CheckSessionTimeout(string sessionId)
        {
            var where = new Where<TB_Day_Exchage_Info>();
            where.And(d => (d.SessionId == sessionId));
            where.And(d => (d.LoginTime > DateTime.Now.AddMinutes(sessionTimeout)));
            where.And(d => (d.TransferSTime == null));
            return DB.Context.Exists<TB_Day_Exchage_Info>(where.ToWhereClip());
        }

        /// <summary>
        /// 检测sessionid是否存在
        /// </summary>
        /// <param name="sessionId"></param>
        /// <returns>true 存在  false 不存在</returns>
        public bool CheckSIdExists(string sessionId)
        {
            var where = new Where<TB_Day_Exchage_Info>();
            where.And(d => (d.SessionId == sessionId));
            return DB.Context.Exists<TB_Day_Exchage_Info>(where.ToWhereClip());
        }

        /// <summary>
        /// 检测sessionid是否已被使用
        /// </summary>
        /// <param name="sessionId"></param>
        /// <returns>true 已经被使用， false 尚未被使用</returns>
        public bool CheckSIdUsed(string sessionId)
        {
            var where = new Where<TB_Day_Exchage_Info>();
            where.And(d => (d.SessionId == sessionId));
            where.And(d => (d.TransferSTime != null));
            return DB.Context.Exists<TB_Day_Exchage_Info>(where.ToWhereClip());
        }


        /// <summary>
        /// 执行积分兑换操作
        /// </summary>
        /// <param name="exInfo">转赠数据</param>
        /// <param name="transferPoint">要转赠的积分数值</param>
        /// <param name="sms">短信验证码</param>
        /// <returns>空为成功， 其他错误信息 1、没有找到可用的受赠人 2. Exception.Message</returns>
        public string Exchange(TB_Day_Exchage_Info exInfo, int transferPoint, string sms
            ,string operateUserName, int operateUseId)
        {
            string rel = "";
            ExchangeLogic exLogic = new ExchangeLogic();
            FailLogic fLogic = new FailLogic();
            JFBLL jfBll = new JFBLL(exInfo.SessionId);
            try
            {
                DoneeLogic dLogic = new DoneeLogic();
                TB_Donee tempDonee = dLogic.GetCanTransferModel(transferPoint);
                if (tempDonee == null)
                {
                    rel = FailReason.GetReasonStr(FailReason.EXCHANGE_PERSON_NOTFOUND_ERR);

                    TB_Fail_Info tfInfo = new TB_Fail_Info()
                    {
                        FailSTime = DateTime.Now,
                        OperateId = operateUseId,
                        OperateName = operateUserName,
                        Phone = exInfo.Phone,
                        Pwd = "",
                        Reason = FailReason.GetReasonStr(FailReason.EXCHANGE_PERSON_NOTFOUND_ERR),
                        ReasonId = FailReason.EXCHANGE_PERSON_NOTFOUND_ERR,
                        Remark = "",
                        SessionId = exInfo.SessionId
                    };

                    fLogic.Insert(tfInfo);

                    return rel;
                }
                
                bool suc = jfBll.transferPoint(tempDonee, sms, transferPoint);
                if (suc)
                {
                    //更新转让人信息
                    exInfo.doneephone = tempDonee.Phone;
                    exInfo.TransferPoint = transferPoint;
                    exInfo.TransferSTime = DateTime.Now;
                    exInfo.RestPoint = exInfo.Integar - transferPoint;
                    exInfo.OperateId = operateUseId;
                    exInfo.OperateName = operateUserName;
                    exLogic.Update(exInfo);

                    //更新受赠人信息
                    tempDonee.NewIntegra += transferPoint;
                    dLogic.Update(tempDonee);
                }

            }
            catch (Exception ex)
            {
                //失败情况保存到数据库
                FailInfo fInfo = null;
                try
                {
                    fInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<FailInfo>(ex.Message);
                }
                catch (Exception ex1)
                {
                    fInfo = new FailInfo()
                    {
                        FailId = FailReason.LOGIN_UNKNOWN_ERR,
                        FailReason = FailReason.GetReasonStr(FailReason.LOGIN_UNKNOWN_ERR),
                        Remark = ex1.Message
                    };
                }

                
                TB_Fail_Info tfInfo = new TB_Fail_Info()
                {
                    FailSTime = DateTime.Now,
                    OperateId = operateUseId,
                    OperateName = operateUserName,
                    Phone = exInfo.Phone,
                    Pwd = "",
                    Reason = fInfo.FailReason,
                    ReasonId = fInfo.FailId,
                    Remark = fInfo.Remark,
                    SessionId = exInfo.SessionId
                };
                fLogic.Insert(tfInfo);
                //失败情况保存到数据库

                rel = ex.Message;
            }
            return rel;
        }

        public string LoginAndCheckIntegra(string uPhone, string uPwd, int operateId, string operateName
            , out string integra, out string sId)
        {
            integra = "-1";
            sId = FormsAuthentication.HashPasswordForStoringInConfigFile(Guid.NewGuid().ToString(), "MD5");
            string radom = "";
            string rel = "";
            try
            {
                JFBLL jfBll = null;
                JFSessionLogic jfLogic = new JFSessionLogic();
                string jfSessionId = jfLogic.GetJFSessionId(uPhone);

                Hashtable ht = new Hashtable();
                if (!string.IsNullOrEmpty(jfSessionId))
                {
                    jfBll = new JFBLL(uPhone, uPwd, sId, jfSessionId);
                    ht = jfBll.UserEasyLogin();
                }
                else
                {

                    CodeRepoLogic crLogic = new CodeRepoLogic();
                    int timeOut = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["RadonTimeOut"]);
                    TB_Code_Repo codeRepo = crLogic.GetModelByNewId(timeOut);
                    if (codeRepo != null)
                    {
                        sId = codeRepo.SessionId;
                        radom = codeRepo.CodeStr;
                    }

                    jfBll = new JFBLL(uPhone, uPwd, sId);

                    if (string.IsNullOrEmpty(radom))
                    {
                        ht = jfBll.UseCommonLogin();
                    }
                    else
                    {
                        codeRepo.CodeState = CodeState.USERD;
                        crLogic.Update(codeRepo);

                        ht = jfBll.UserFastLogin(radom);
                    }
                }

                integra = ht["integra"].ToString();

                TB_Day_Exchage_Info exchangeInfo = new TB_Day_Exchage_Info()
                {
                    Phone = uPhone,
                    LoginOperId = operateId,
                    LoginTime = DateTime.Now,
                    SessionId = sId,
                    Integar = Convert.ToInt32(integra)
                };

                ExchangeLogic exLogic = new ExchangeLogic();
                int indentity = exLogic.Insert(exchangeInfo);
                exchangeInfo.ExchangeId = indentity;

            }
            catch (Exception ex)
            {
                Log.PrintLog(ex.Message);

                //失败情况保存到数据库
                FailInfo fInfo = null;
                try
                {
                    fInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<FailInfo>(ex.Message);
                }
                catch
                {
                    fInfo = new FailInfo() { 
                        FailId = FailReason.LOGIN_UNKNOWN_ERR,
                        FailReason = FailReason.GetReasonStr(FailReason.LOGIN_UNKNOWN_ERR),
                        Remark = ex.Message
                    };
                }

                FailLogic fLogic = new FailLogic();
                TB_Fail_Info tfInfo = new TB_Fail_Info() {
                    FailSTime = DateTime.Now,
                    OperateId = operateId,
                    OperateName = operateName,
                    Phone = uPhone,
                    Pwd = uPwd,
                    Reason = fInfo.FailReason,
                    ReasonId = fInfo.FailId,
                    Remark = fInfo.Remark,
                    SessionId = sId
                };
                fLogic.Insert(tfInfo);
                //失败情况保存到数据库

                rel = ex.Message;
            }
            return rel;

        }

    }
    
}
